<?php

class EmailMessage extends Model
{
	var $id = null;
	var $subject;	
	var $body;
	var $active = 1;
	var $sent_at;
	var $creator_id;
	var $created_at;
	var $updater_id;
	var $updated_at;
	
	function EmailMessage()
	{
		parent::Model();
		$this->created_at = date_db_format();
	}
	
	function get_by_id($id)
	{
		$this->db->select('e.id, e.subject, e.body, e.sent_at, e.creator_id, e.created_at, e.updater_id, e.updated_at, u.firstname as creator_firstname, u.name as creator_name, u2.firstname as updater_firstname, u2.name as updater_name')
			     ->from('email_message e')
			     ->join('user u', 'e.creator_id = u.id')
			     ->join('user u2', 'e.updater_id = u2.id')
			     ->where('e.id', $id)
			     ->where('e.active', 1);
		$query = $this->db->get();
		return $query->row();
	}
	
	function plain_get($id)
	{
		$this->db->select('id, subject, body, sent_at, creator_id, created_at, updater_id, updated_at')
			     ->from('email_message')
			     ->where('id', $id)
			     ->where('active', 1);
		$query = $this->db->get();
		return $query->row();
	}

	function all()
	{
		$this->db->select('e.id, e.subject, e.sent_at, e.creator_id, e.created_at, e.updater_id, e.updated_at, u.firstname as creator_firstname, u.name as creator_name, u2.firstname as updater_firstname, u2.name as updater_name')
			     ->from('email_message e')
			     ->join('user u', 'e.creator_id = u.id')
			     ->join('user u2', 'e.updater_id = u2.id')
			     ->where('e.active', 1)
			     ->order_by('e.sent_at DESC');
		$query = $this->db->get();
		return $query->result();
	}
	
	function update($object, $data)
	{
		if (isset($data['subject'])) $object->subject = clean_str($data['subject']);
		if (isset($data['body'])) $object->body = clean_str($data['body']);
		
		// check
		$errors = array();
		if (!$object->subject)   $errors[] = 'Le sujet ne peut pas être vide';
		if (!$object->body)      $errors[] = 'Le contenu ne peut pas être vide';
		return $errors;
	}
	
	function save($object)
	{
		if ($object->id == null) {
			return $this->db->insert('email_message', $object);
		}
		else {
			$this->db->where('id', $object->id);
			return $this->db->update('email_message', $object); 
		}
	}
	
	function delete($id)
	{
		$sql = 'UPDATE email_message
		        SET active = 0
		        WHERE id = '.intval($id).';';
		return $this->db->query($sql);
	}
}
